﻿using System.Threading.Tasks;
using System.Net;
using BeetleX;
using BeetleX.EventArgs;
using Microsoft.Extensions.Logging;
namespace Athena.Transport.BeetleX
{
    using Codec;
    using Message;

    public class BeetleXTransportMessageListener : ITransportMessageListener
    {
        private readonly IRpcMessageDecoder _rpcMessageDecoder;
        private readonly IRpcMessageEncoder _rpcMessageEncoder;
        private readonly ILoggerFactory _loggerFactory;
        private readonly ILogger _logger;

        private IServer beetleXServer;

        public event ReceivedDelegate Received;

        public BeetleXTransportMessageListener(IRpcMessageCodecFactory rpcMessageCodecFactory, ILoggerFactory loggerFactory)
        {
            _rpcMessageDecoder = rpcMessageCodecFactory.CreateDecoder();
            _rpcMessageEncoder = rpcMessageCodecFactory.CreateEncoder();
            _loggerFactory = loggerFactory;
            _logger = _loggerFactory.CreateLogger<BeetleXTransportMessageListener>();
        }

        public Task StartAsync(EndPoint endPoint)
        {
            var serverOptions = new ServerOptions();
            serverOptions.DefaultListen.Port = int.Parse(endPoint.ToString().Split(':')[1]);
            beetleXServer = SocketFactory.CreateTcpServer(new BeetleXRpcServiceHandler(_rpcMessageEncoder, _rpcMessageDecoder, _loggerFactory.CreateLogger<BeetleXRpcServiceHandler>(), async (sender, message) =>
            {
                await OnReceived(sender, message);
            }), null, serverOptions);
            beetleXServer.Open();
            _logger.LogInformation(beetleXServer.ToString());
            return Task.CompletedTask;
        }

        public async Task OnReceived(ITransportMessageSender transportMessageSender, RpcTransportMessage rpcTransportMessage)
        {
            if (Received == null)
            {
                return;
            }
            await Received(transportMessageSender, rpcTransportMessage);
        }
    }
}
